import { Component, OnInit } from '@angular/core';
import { JsonApiService } from "app/core/api/json-api.service"; //http请求配置引入
import { config } from '../../shared/smartadmin.config';

declare var $: any;
declare var echarts: any;
@Component({
	selector: 'sa-weight-error-rate',
	templateUrl: './weight-error-rate.component.html',
	styleUrls: ['./weight-error-rate.css']
})
export class WeightErrorRateComponent implements OnInit {
	tableData: any[] = []; //table数据
	totalCount: number = 0; //分页总条数
	curPage: number = 1; //分页当前页
	pageSize: number = 10; //内置的分页每页条数
	searchKey: string = ''; //搜索keyword
	carList: any[] = []; //车辆数据
	carNumber:number|string = '';	//车牌号
	companyId: string = ''; //公司
	companyList: any[] = []; //公司数据
	deviceId: string = ''; //设备ID
	startTime: string = ''; //开始时间
	endTime: string = ''; //结束时间
	curBtn: string = '1'; //当前激活按钮
	mapModel: any = {
		total: 0,
		pass: 0,
		unpass: 0,
		carNumber: '全部',
		deviceId: ''
	};
	activeSelected: string = ''; //row高亮
	selected: any = []; //row选择的数据
	selectedCompanyName: string = ''; //公司名称
	selectedCompanyId: string = ''; //公司id
	dataGrounding: string = ''; //导出分组
	dataSort: string = 'dateDESC'; //导出分类
	useTypeL1: string = ''; //useTypeL1  select值
	useTypeL2: string = ''; //useTypeL2  select值
	carTypeDetailList: any = []; //useTypeL2数据
	carTypeList = carTypeListObj.carTypeList
	carUseList = carTypeListObj.carUseList
	carDeatailUseList = carTypeListObj.carDeatailUseList
	constructor(private jsonApiService: JsonApiService) {}

	ngOnInit() {
		this.initMap();		
		this.initDate().then(() => this.load());
	}
	ngOnDestroy() {
		document.onclick = null;
	}
	//初始化统计图
	initMap() {
		this.dateSelect('1');
	}
	//查看统计图
	rowSelectEvent(row, index) {
		if(this.activeSelected === row.id) {
			this.activeSelected = '';
			this.mapModel.carNumber = '全部';
			this.mapModel.deviceId = '';
			this.dateSelect('1');
		} else {
			this.activeSelected = row.id;
			this.mapModel.carNumber = row.carNumber;
			this.mapModel.deviceId = row.deviceId;
			this.dateSelect('1');
		}
	}
	dateSelect(type) {
		this.curBtn = type;
		let curTime = new Date();
		let curDate = common.getTimeDay(curTime);
		let startTime, endTime;
		switch(type) {
			case '1':
				startTime = curDate + ' 00:00:00';
				endTime = curDate + ' 23:59:59';
				break;
			case '2':
				curDate = common.getTimeDay(new Date(curTime.getTime() - 3600 * 24 * 1000 * 1));
				startTime = curDate + ' 00:00:00';
				endTime = curDate + ' 23:59:59';
				break;
			case '3':
				curDate = common.getTimeDay(new Date(curTime.getTime() - 3600 * 24 * 1000 * 2));
				startTime = curDate + ' 00:00:00';
				endTime = curDate + ' 23:59:59';
				break;
			case '4':
				startTime = common.getTimeDay(new Date(curTime.getTime() - 3600 * 24 * 1000 * 2)) + ' 00:00:00';
				endTime = curDate + ' 23:59:59';
				break;
			case '5':
				startTime = common.getTimeDay(new Date(curTime.getTime() - 3600 * 24 * 1000 * 9)) + ' 00:00:00';
				endTime = curDate + ' 23:59:59';
				break;
			case '6':
				startTime = common.getTimeDay(new Date(curTime.getTime() - 3600 * 24 * 1000 * 29)) + ' 00:00:00';
				endTime = curDate + ' 23:59:59';
				break;
			default:
				startTime = '';
				endTime = '';
				break;
		}
		let chart = echarts.init(document.getElementById("weight_map"));
		let option = {
			title: {
				text: '无数据',
				subtext: '误差率',
				x: 'center',
				y: 'center',
				textStyle: {
					fontWeight: 'normal',
					color: '#0580f2',
					fontSize: '24'
				}
			},
			color: ['rgba(176, 212, 251, 1)'],
			legend: {
				show: true,
				itemGap: 12,
				data: ['不合格趟数', '合格趟数'],
				bottom:4
			},
			series: [{
				name: 'Line 1',
				type: 'pie',
				clockWise: true,
				radius: ['50%', '66%'],
				itemStyle: {
					normal: {
						label: {
							show: false
						},
						labelLine: {
							show: false
						}
					}
				},
				hoverAnimation: false,
				data: [{
					value: this.mapModel.unpass,
					name: '不合格趟数',
					itemStyle: {
						normal: {
							color: { // 完成的圆环的颜色
								colorStops: [{
									offset: 0,
									color: '#00cefc' // 0% 处的颜色
								}, {
									offset: 1,
									color: '#367bec' // 100% 处的颜色
								}]
							},
							label: {
								show: false
							},
							labelLine: {
								show: false
							}
						}
					}
				}, {
					name: '合格趟数',
					value: this.mapModel.pass
				}]
			}]
		}
		chart.setOption(option);
		let reqdata = 'startDate=' + startTime + '&endDate=' + endTime + '&deviceId=' + this.mapModel.deviceId;
		this.jsonApiService.http("weightdeviation/countWeightBridge.html", reqdata).subscribe(data => {
			if(data.success) {
				this.mapModel.total = data.data.totleNumber;
				this.mapModel.pass = data.data.passNumber;
				this.mapModel.unpass = data.data.failNumber;
				let percent;
				if(!this.mapModel.total) {
					percent = '无数据'
				} else {
					percent = ((this.mapModel.unpass / this.mapModel.total) * 100).toFixed(0) + '%';
				}
				let seriesData = [{
					value: this.mapModel.unpass,
					name: '不合格趟数',
					itemStyle: {
						normal: {
							color: { // 完成的圆环的颜色
								colorStops: [{
									offset: 0,
									color: '#00cefc' // 0% 处的颜色
								}, {
									offset: 1,
									color: '#367bec' // 100% 处的颜色
								}]
							},
							label: {
								show: false
							},
							labelLine: {
								show: false
							}
						}
					}
				}, {
					name: '合格趟数',
					value: this.mapModel.pass
				}]
				chart.setOption({
					title: {
						text: percent
					},
					series: [{
						data: seriesData
					}]
				});
				$(window).resize(chart.resize);
			} else {
				this.jsonApiService.message(data.message);
			}
		})
	}
	//车辆用途change回调
	carUseTypeL1Change() {
		this.carTypeDetailList = [];
		this.useTypeL2 = '';
		for(let item of this.carTypeList) {
			if(item.id === this.useTypeL1) {
				this.carTypeDetailList = item.children;
				break;
			}
		}
	}
	//导出提交
	exportSubmit() {
		this.startTime = $('#datetimepicker1').val();
		this.endTime = $('#datetimepicker2').val();
		var temdate = new Date();
		var nowTime = temdate.getTime().toString();
		var parameters = {
			deviceId: this.deviceId,
			startTime: this.startTime,
			endTime: this.endTime,
			fileName: "车辆地磅重量差值比例统计" + nowTime,
			group: this.dataGrounding,
			sort: this.dataSort,
			useTypeL1: this.useTypeL1,
			useTypeL2: this.useTypeL2,
			companyId: this.selectedCompanyId
		}
		let timeCheck = common.correctTime(parameters, ['fileName','group','sort']);
		if(!timeCheck.status) {
			this.jsonApiService.message(timeCheck.message);
			return;
		}
		common.exprotDataFile(parameters, 'param', config.BaseURL + 'weightdeviation/weightdeviationexport.html')
	}
	//导出取消
	cancelExport(val) {
		val.hide()
	}
	//导出
	export_totle(val) {
		val.show()
	}
	getTime(date) {
		var year = date.getFullYear();
		var month = (date.getMonth() + 1) < 10 ? "0" + (date.getMonth() + 1) : (date.getMonth() + 1);
		var day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
		return year + "-" + month + "-" + day;
	}
	//初始化时间
	initDate() {
		var that = this;
		return new Promise(function(resolve, reject) {
			System.import('assets/js/datepicker/js/bootstrap-datetimepicker.min.js').then(
				() => {
					System.import('assets/js/datepicker/locales/bootstrap-datetimepicker.zh-CN.js').then(() => {
						$("#datetimepicker1").datetimepicker({ //时间插件
							format: "yyyy-mm-dd",
							language: "zh-CN",
							autoclose: true,
							minView: 2
						}).on("changeDate", function(e) {
							var date = e.date;
							var time = that.getTime(date);
							$("#datetimepicker2").datetimepicker("setStartDate", time);
						});
						$("#datetimepicker2").datetimepicker({ //时间插件
							format: "yyyy-mm-dd",
							language: "zh-CN",
							autoclose: true,
							minView: 2
						}).on("changeDate", function(e) {
							var date = e.date;
							var time = that.getTime(date);
							$("#datetimepicker1").datetimepicker("setEndDate", time);
						});
						//						var date = new Date();
						//						$("#datetimepicker2").val(that.getTime(date));//当前时间
						//						date.setDate(date.getDate() - 7);//设置前一天
						//						$("#datetimepicker1").val(that.getTime(date));
						resolve();
					});
				}
			);
		})
	}
	//刷新
	refresh() {
		this.load();
	}
	//查询
	search_data() {
		this.curPage = 1;
		this.load();
	}
	//初始化加载list数据
	load() {
		this.activeSelected = '';
		this.startTime = $('#datetimepicker1').val();
		this.endTime = $('#datetimepicker2').val();
		let timeCheck = common.correctTimeParams(this.startTime, this.endTime, 0);
		if(!timeCheck.status) {
			this.jsonApiService.message(timeCheck.message);
			return;
		}
		let data = {
			pageSize: this.pageSize,
			nowPage: this.curPage,
			parameters: {
				useTypeL1: this.useTypeL1,
				useTypeL2: this.useTypeL2,
				companyId: this.selectedCompanyId,
				startTime: this.startTime,
				endTime: this.endTime,
				deviceId: this.deviceId
			}
		}
		let reqdata = 'gridPager=' + JSON.stringify(data);
		this.jsonApiService.http("weightdeviation/list.html", reqdata).subscribe(data => {
			if(data.exhibitDatas) {
				for(let item of data.exhibitDatas) {
					item.useTypeL1 = this.getUseTypeNameL1(item.useTypeL1);
					item.useTypeL2 = this.getUseTypeNameL2(item.useTypeL2);
					item.weight = common.twoDecimal(item.weight);
					item.weighbridge = common.twoDecimal(item.weighbridge);
				}
			}
			this.tableData = data.exhibitDatas;
			this.totalCount = data.recordCount;
		})
	}
	getUseTypeNameL1(key) {
		if(key) {
			return this.carUseList[key];
		} else {
			return '';
		}
	}
	getUseTypeNameL2(key) {
		if(key) {
			return this.carDeatailUseList[key];
		} else {
			return '';
		}
	}
	//删除所选时间
	del_date() {
		this.startTime = '';
		this.endTime = '';
		$("#datetimepicker1").val('').change();
		$("#datetimepicker2").val('').change();
		$("#datetimepicker2").datetimepicker("setStartDate", null);
		$("#datetimepicker1").datetimepicker("setEndDate", null);
	}
	//分页回调
	paginate(e) {
		this.curPage = e.page + 1;
		this.pageSize = e.rows;
		this.load();
	}
	//公司选中回调
	companySelected(data){
		this.selectedCompanyId = data.companyId;
		this.selectedCompanyName = data.companyName;
		this.deviceId = data.deviceId;
		this.carNumber = data.carNumber;
		if(this.deviceId){
			$("#useTypeL1").attr("disabled", "disabled");
			$("#useTypeL1").css("cursor", "not-allowed");
			$("#useTypeL2").attr("disabled", "disabled");
			$("#useTypeL2").css("cursor", "not-allowed");
		}else{
			$("#useTypeL1").removeAttr("disabled");
			$("#useTypeL1").css("cursor", "pointer");
			$("#useTypeL2").removeAttr("disabled");
			$("#useTypeL2").css("cursor", "pointer");
		}		
	}
}